<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-row>
          <el-button type="success" @click="handleCreate"
          >&emsp;新增&emsp;
          </el-button
          >
        </el-row>
      </div>
      <div v-loading="listLoading" class="item">
        <el-table
          ref="dataList"
          :data="menuList"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          border
          class="w-full mb-4"
          row-key="id"
        >
          <el-table-column label="序号" prop="id"></el-table-column>
          <el-table-column label="活动名称" prop="name"></el-table-column>
          <el-table-column label="活动标题" prop="title"></el-table-column>
          <el-table-column label="活动内容" prop="content"></el-table-column>
          <el-table-column label="活动展示图" prop="picture">
            <template slot-scope="scope">
              <el-image :src="scope.row.picture" fit="fill" class="avatar">
                <div slot="error" class="image-slot">
                    <i class="el-icon-picture-outline"></i>
                </div>
              </el-image>
            </template>
          </el-table-column>
          <el-table-column label="详情图" prop="detail_picture">
            <template slot-scope="scope">
              <el-image :src="scope.row.detail_picture" fit="fill" class="avatar">
                <div slot="error" class="image-slot">
                    <i class="el-icon-picture-outline"></i>
                </div>
              </el-image>
            </template>
          </el-table-column>
          <el-table-column label="展示URL" prop="h5_url"></el-table-column>
          <el-table-column label="添加时间" prop="created_at"></el-table-column>

          <el-table-column label="操作" width="260px">
            <template slot-scope="scope">
              <el-button
                v-if="scope.row.status === 0"
                icon="el-icon-edit"
                plain
                size="mini"
                type="primary"
                @click="handleUpdate(scope.row)"
              >编辑
              </el-button>
              <!-- <el-button
                icon="el-icon-delete"
                plain
                size="mini"
                type="danger"
                @click="handleDelete(scope.row)"
              >删除
              </el-button> -->
              <el-button
                icon="el-icon-position"
                plain
                size="mini"
                type="success"
                @click="handleSend(scope.row)"
              >发送
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <cus-pagination
          :limit.sync="listQuery.perPage"
          :page.sync="listQuery.page"
          :total="total"
          @pagination="getList"
        />
      </div>
    </el-card>
    <!-- 删除弹框 -->
    <el-dialog
      :visible.sync="deleteDialogVisible"
      title="确定删除吗?"
      width="435px"
    >
      <span style=""
      ><em style="font-style:normal;color:red">删除后不可恢复</em
      >，你还要继续吗？</span
      >
      <div slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmDelete">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 新增编辑弹框 -->
    <el-dialog
      v-dialogDrag
      :title="titleMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      @close="handleCloseDialog"
    >
      <el-form
        ref="editRulesForm"
        :model="editRulesForm"
        :rules="editRulesFormRules"
        class="demo-ruleForm"
        label-width="120px"
      >
        <el-form-item label="活动名称" prop="name">
          <el-input
            v-model="editRulesForm.name"
            clearable
            maxlength="10"
            show-word-limit
            placeholder="请输入活动名称(1-10个字符)"
          ></el-input>
        </el-form-item>
        <el-form-item label="活动标题" prop="title">
          <el-input
            v-model="editRulesForm.title"
            clearable
            maxlength="25"
            show-word-limit
            placeholder="请输入活动名称(1-25个字符)"
          ></el-input>
        </el-form-item>
        <el-form-item label="活动内容" prop="content">
          <el-input
            v-model="editRulesForm.content"
            clearable
            maxlength="50"
            minlength="10"
            show-word-limit
            placeholder="请输入活动内容(10-50个字符)"
          ></el-input>
        </el-form-item>
        <el-form-item label="展示图片" prop="picture">
          <el-upload
              :http-request="customizeUpload"
              :on-success="handleSuccess1"
              :show-file-list="false"
              action=""
              class="avatar-uploader"
          >
              <img v-if="editRulesForm.picture"
                  :src="editRulesForm.picture"
                  class="avatar"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="活动类型" prop="show_type">
          <el-select v-model="editRulesForm.show_type" placeholder="请选择" clearable filterable @change="handleChange">
            <el-option v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
          
        </el-form-item>

        <el-form-item label="详情图" prop="detail_picture" v-if="editRulesForm.show_type === 2">
          <el-upload
              :http-request="customizeUpload"
              :on-success="handleSuccess2"
              :show-file-list="false"
              action=""
              class="avatar-uploader"
          >
              <img v-if="editRulesForm.detail_picture"
                  :src="editRulesForm.detail_picture"
                  class="avatar"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="外部链接" prop="h5_url" v-if="editRulesForm.show_type === 3">
          <el-input
            v-model="editRulesForm.h5_url"
            clearable
            maxlength="50"
            minlength="10"
            show-word-limit
            placeholder="请输入"
          ></el-input>
        </el-form-item>


        <el-form-item>
          <el-button @click="dialogFormVisible = false">返回</el-button>
          <el-button type="primary" @click="submitForm('editRulesForm')"
          >提交
          </el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 发送弹出框 -->
    <el-dialog v-dialogDrag :visible.sync="sendVisible" title="发送">
      <span style=""><em style="font-style:normal;color:red">确认发送</em>，发送后不可修改</span>
      <div slot="footer" class="dialog-footer">
        <el-button @click="sendVisible = false">取消</el-button>
          <el-button type="primary" @click="sendSubmit">发送</el-button>
      </div>
      
    </el-dialog>
  </div>
</template>

<script>
import { listData, postAddData, postSendData, putEditData } from '@/api/sys/activeMessage'

import wangEditor from 'wangeditor'

const notice = {
  type: 'success',
  message: '操作成功',
  position: 'bottom-right',
  showClose: false,
  duration: 3000
}

export default {
  data() {
    return {

      sendContent: undefined,
      sendMessageType: 1,
      chooseUser: [
        { value: 1, label: '全部' },
        { value: 2, label: '指定' },
        { value: 3, label: '男性' },
        { value: 4, label: '女性' }
      ],
      sendVisible: false,
      sendFormRules: {
        user_type: [
          { required: true, message: '请选择用户类型', trigger: 'change' }
        ]
        // user_codes:[{required:true,message:'请输入用户ID',trigger:'blur'}]
      },
      sendForm: {
        user_type: undefined,
        user_codes: undefined
      },

      // 上传图片
      dialogImageUrl: '',
      // 富文本框
      editorOption: {},
      // 要修改的当前行的id
      row_id: 0,
      // 黑名单类别
      blackList: [
        { value: 1, label: '1' },
        { value: 2, label: '4' },
        { value: 3, label: '6' },
        { value: 4, label: '3' },
        { value: 5, label: '5' }
      ],
      // 选中的黑名单类别
      checkBlackList: [],
      provinceList: [],
      cityList: [],
      // 表单规则
      editRulesFormRules: {
        name: [
          { required: true, message: '请输入活动名称', trigger: 'change' },
          {
            min: 1,
            max: 10,
            message: '活动名称控制在1-10个字符内',
            trigger: 'blur'
          }
        ],
        title: [
          { required: true, message: '请输入标题文字', trigger: 'change' },
          {
            min: 1,
            max: 30,
            message: '标题文字控制在1-25个字符内',
            trigger: 'blur'
          }
        ],
        content: [
          { required: true, message: '请输入活动内容', trigger: 'change' },
          {
            min: 10,
            max: 50,
            message: '活动内容控制在10-50个字符内',
            trigger: 'blur'
          }
        ],
        picture: [
          { required: true, message: '请上传展示图', trigger: 'change' }
        ],
        show_type: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ],
        h5_url: [
          { required: true, message: '请输入外部链接', trigger: 'change' }
        ],
        detail_picture: [
          { required: true, message: '请上传详情图', trigger: 'change' }
        ]
      },
      // 受限类型
      limit_typeList: [
        { value: 0, label: '全部' },
        { value: 1, label: 'IP' },
        { value: 2, label: '归属地' }
      ],
      editRulesForm: {
        title: '',
        show_type: 1,
        content: '',
        name: '',
        detail_picture: '',
        picture: '',
        h5_url: ''
      },
      dialogStatus: '',
      // dialog的头部信息
      titleMap: {
        update: '编辑',
        create: '新增'
      },
      pirtureList: [],
      uploadPirtureList: [],
      dialogFormVisible: false,
      deleteDialogVisible: false,
      listLoading: false,
      menuList: [],
      limitList: [],
      listQuery: {
        page: 1,
        perpage: 10
      },
      total: 0,
      // 勾选内容
      multipleSelection: [],
      // 要删除的内容的ids
      dataIds: '',
      timeout: null, // 定时器
      options: [
        {
          label: '普通',
          value: 1
        },
        {
          label: '详情页',
          value: 2
        },
        {
          label: 'H5页面',
          value: 3
        }
      ]
    }
  },
  created() {
    this.getList()
  },
  methods: {
    handleChange(val) {},
    handleSend(row) {
      this.row_id = row.id
      this.sendVisible = true
    },
    sendSubmit() {
      postSendData(this.row_id).then(response => {
        if (response.code === 200) {
          this.sendVisible = false
          this.$notify({
            type: 'success',
            message: '操作成功',
            position: 'bottom-right',
            showClose: false,
            duration: 3000
          })
        }
      })
    },
    getList() {
      this.listLoading = true
      for (let key in this.listQuery) {
        this.listQuery[key] = this.listQuery[key] === '' ? undefined : this.listQuery[key]
      }
      listData(this.listQuery).then(response => {
        this.menuList = response.data.list
        this.total = response.data.meta.total
        this.listLoading = false
      })
    },
    // 点击新增
    handleCreate() {
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    // 点击编辑
    handleUpdate(row) {
      this.row_id = row.id
      this.editRulesForm.title = row.title
      this.editRulesForm.name = row.name
      this.editRulesForm.show_type = row.show_type
      this.editRulesForm.content = row.content
      this.editRulesForm.picture = row.picture
      if(this.editRulesForm.show_type === 2) {
        this.editRulesForm.detail_picture = row.detail_picture
      }
      if(this.editRulesForm.show_type === 3) {
        this.editRulesForm.h5_url = row.h5_url
      }
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
    },

    // 重置表单内容
    resetForm(formName) {
      this.$nextTick(() => {
        if (this.$refs[formName] !== undefined) {
          this.$refs[formName].resetFields()
        }
        this.cityList = []
        this.editRulesForm = {
          title: undefined,
          show_type: 1,
          content: undefined
        }
      })
    },
    // 移除图片
    handleRemove(file, fileList) {
      this.editRulesForm = fileList
    },
    handleSuccess1() {
      console.log(this.ossLastImgUrl)
      this.editRulesForm.picture = this.ossLastImgUrl
      console.log(this.editRulesForm.picture)
    },
    handleSuccess2() {
      this.editRulesForm.detail_picture = this.ossLastImgUrl
    },
    handleCloseDialog() {
      this.editRulesForm = {
        title: undefined,
        show_type: 1,
        content: undefined,
        name: undefined,
        detail_picture: undefined,
        picture: undefined,
        h5_url: undefined
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.dialogStatus === 'create') {
            let obj = JSON.parse(JSON.stringify(this.editRulesForm))
            postAddData(obj).then(response => {
              if (response.code === 200) {
                this.getList()
                this.dialogFormVisible = false
                this.$notify(notice)
              }
            })
          } else {
            let obj = JSON.parse(JSON.stringify(this.editRulesForm))
            // 判断活动类型为详情或h5页清空不需要的数据
            if(this.editRulesForm.show_type === 1 || this.editRulesForm.show_type === 2) {
              obj.h5_url = undefined
            }
            // if(v.show_type === 3) {
            //   obj.detail_picture = undefined
            // }
            if(this.editRulesForm.show_type === 1 || this.editRulesForm.show_type === 3) {
              obj.detail_picture = undefined
            }
            putEditData(this.row_id, obj).then(response => {
              if (response.code === 200) {
                this.getList()
                this.dialogFormVisible = false
                this.$notify(notice)
              }
            })
          }
        }
      })
    },
    // 点击单个删除
    handleDelete(row) {
      this.dataIds = { ids: `${row.id}` }
      this.deleteDialogVisible = true
    },
    // 确定删除
    confirmDelete() {
      if (this.multipleSelection.length !== 0) {
        let ids = ''
        for (let key in this.multipleSelection) {
          ids += `${this.multipleSelection[key].id},`
        }
        ids = ids.substring(0, ids.length - 1)
        this.dataIds = { ids: ids }
      }

      this.deleteDialogVisible = false
      deleteData(this.dataIds).then(response => {
        if (response.code === 200) {
          this.getList()
          this.deleteDialogVisible = false
          this.$notify({
            type: 'success',
            message: '操作成功',
            position: 'bottom-right',
            showClose: false,
            duration: 3000
          })
        } else {
          this.$message({
            message: response.message,
            type: 'error'
          })
        }
      })
    }
  },
  watch: {
    sendVisible(value) {
      if (!value) {
        this.$refs['sendForm'].resetFields()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar-uploader {
  border-radius : 6px;
  cursor        : pointer;
  position      : relative;
  overflow      : hidden;
}

.avatar-uploader .el-upload:hover {
  border-color : #409EFF;
}

.avatar-uploader-icon {
  border        : 1px dashed #d9d9d9;
  font-size   : 28px;
  color       : #8c939d;
  width       : 178px;
  height      : 178px;
  line-height : 178px;
  text-align  : center;
}

.avatar {
  width   : 178px;
  height  : 178px;
  display : block;
}
</style>
